package com.ellricky.newtv

import android.content.pm.ActivityInfo
import android.graphics.Color
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.andr.common.ui.activity.BaseActivity
import com.andr.common.ui.mvp.BasePresenter
import com.angcyo.tablayout.DslTabLayout
import com.ellricky.baselib.BaseConstant
import com.ellricky.baselib.adapter.GridItemDecoration
import com.ellricky.baselib.cache.LocalCacheUtil
import com.ellricky.baselib.entity.newtv.ClassInfo
import com.ellricky.baselib.entity.newtv.TvUserInfo
import com.ellricky.baselib.http.HttpUtils
import com.ellricky.baselib.util.EAppUtil
import com.ellricky.baselib.util.NewEListCallback
import com.ellricky.baselib.util.jump
import com.ellricky.newtv.adapter.CourseFileAdapter
import com.ellricky.newtv.adapter.CoursePreTypeAdapter
import com.ellricky.newtv.adapter.TYPE_NORMAL
import com.ellricky.newtv.adapter.TYPE_RECORD
import com.ellricky.newtv.bean.TvCourseFile
import com.ellricky.newtv.bean.TvCourseStage
import com.ellricky.newtv.bean.TvCourseType
import com.ellricky.newtv.const.TvConst
import com.ellricky.newtv.utils.CacheToken
import com.ellricky.newtv.utils.SpacesItemDecoration
import kotlinx.android.synthetic.main.activity_new_tv_pre_lesson.*

class NewTvPreLessonActivity : BaseActivity<Void, BasePresenter<Void>>() {

    private val from: Int by lazy {
        intent.getIntExtra(BaseConstant.KEY_FROM, TYPE_NORMAL)
    }

    private val classId: String by lazy {
        intent.getStringExtra(BaseConstant.KEY_ID) ?: ""
    }

    private val courseTypeAdapter by lazy {
        CoursePreTypeAdapter()
    }

    private val courseFileAdapter by lazy {
        CourseFileAdapter(from)
    }

    private var currentCourseId: String = ""

    override fun setOrientation() {
        this.requestedOrientation =
            ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
    }

    override fun getContentLayout(): Int {
        return R.layout.activity_new_tv_pre_lesson
    }

    override fun initUIView() {
        CacheToken.verifyToken()
        tv_back.setOnClickListener(this)
        tabLayout.setTabLayoutConfig {
            onSelectItemView = { itemView: View, _: Int, select: Boolean, _: Boolean ->
                if (select) {
                    val id = itemView.tag.toString()
                    loadCourseList(currentCourseId, id)
                }
                false
            }
            tabSelectColor = ContextCompat.getColor(this@NewTvPreLessonActivity, R.color.blue)
            tabDeselectColor = ContextCompat.getColor(this@NewTvPreLessonActivity, R.color.white)
        }
        initRv()
        loadCourseTypeData()
    }

    override fun onClickView(v: View) {
        super.onClickView(v)
        when (v.id) {
            R.id.tv_back -> finish()
        }
    }

    private fun loadCourseTypeData() {
        val url = EAppUtil.getTvApiHost()
        val paramMap = mutableMapOf(
            "action" to "courseTypeList",
            "eid" to LocalCacheUtil.getTvUid()
        )
        HttpUtils.getInstance()
            .postFrom(url, paramMap, object : NewEListCallback<TvCourseType>(this, false) {
                override fun onSuccess(data: MutableList<TvCourseType>, msg: String?) {
                    courseTypeAdapter.setList(data)
                    if (data.isNotEmpty()) {
                        val firstCourseType = data.first()
                        loadCourseState(firstCourseType.course_id)
                    }
                }
            }, this)
    }

    private fun loadCourseState(courseId: String) {
        this.currentCourseId = courseId
        val url = EAppUtil.getTvApiHost()
        val paramMap = mutableMapOf(
            "action" to "courseStageList",
            "course_id" to courseId,
            "eid" to LocalCacheUtil.getTvUid()
        )
        HttpUtils.getInstance()
            .postFrom(url, paramMap, object : NewEListCallback<TvCourseStage>(this, false) {
                override fun onSuccess(data: MutableList<TvCourseStage>, msg: String?) {
                    if (tabLayout.childCount > 0) {
                        tabLayout.removeAllViews()
                    }
                    data.forEachIndexed { index, tvCourseStage ->
                        if (index == 0) {
                            loadCourseList(courseId, tvCourseStage.stage_id)
                        }
                        tabLayout.addView(
                            createTextView(
                                index,
                                tvCourseStage.stage_name,
                                tvCourseStage.stage_id
                            )
                        )
                    }
                }

                override fun onErrorCode(code: String?, msg: String?) {
                    super.onErrorCode(code, msg)
                    tabLayout.removeAllViews()
                    courseFileAdapter.setList(arrayListOf())
                }
            }, this)
    }

    fun loadCourseList(courseId: String, courseStageId: String) {
        val url = EAppUtil.getTvApiHost()
        val paramMap = mutableMapOf(
            "action" to "courseWareList",
            "course_type_id" to courseId,
            "course_stage_id" to courseStageId,
            "eid" to LocalCacheUtil.getTvUid()
        )
        if (from == TYPE_RECORD) {
            paramMap["class_id"] = classId
        }
        HttpUtils.getInstance()
            .postFrom(url, paramMap, object : NewEListCallback<TvCourseFile>(this, false) {
                override fun onSuccess(data: MutableList<TvCourseFile>, msg: String?) {
                    courseFileAdapter.setList(data)
                }

                override fun onErrorCode(code: String?, msg: String?) {
                    super.onErrorCode(code, msg)
                    courseFileAdapter.setList(arrayListOf())
                }
            }, this)
    }

    private fun createTextView(index: Int, text: String, id: String): TextView {
        return TextView(this).also {
            it.textSize = 18f
            it.text = text
            it.tag = id
            it.setTextColor(ContextCompat.getColor(this, R.color.white))
            if (index != 0) {
                val params = DslTabLayout.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                )
                params.marginStart = resources.getDimension(R.dimen.dp_30).toInt()
                it.layoutParams = params
            }
        }
    }

    private fun initRv() {
        rv_course_type.layoutManager = LinearLayoutManager(this, RecyclerView.HORIZONTAL, false)
        rv_course_type.adapter = courseTypeAdapter
        rv_course_type.addItemDecoration(SpacesItemDecoration(10))
        courseTypeAdapter.setOnItemClickListener { _,
                                                   view,
                                                   position ->

            val data = courseTypeAdapter.data[position]
            courseTypeAdapter.data.forEach {
                it.isSelect = false
            }
            data.isSelect = true
            courseTypeAdapter.notifyDataSetChanged()
            loadCourseState(data.course_id)
        }

        rv_course_file.layoutManager = GridLayoutManager(this, 4)
        rv_course_file.adapter = courseFileAdapter
        rv_course_file.addItemDecoration(
            GridItemDecoration2(4, 20, 20)
        )
        courseFileAdapter.addChildClickViewIds(R.id.iv_cover, R.id.tv_contact)
        courseFileAdapter.setOnItemChildClickListener { _,
                                                        view,
                                                        position ->
            val data = courseFileAdapter.data[position]

            when (view.id) {
                R.id.tv_contact -> {
                    jump<NewTvConnectActivity>()
                }
                R.id.iv_cover -> {
                    if (!data.ware_ppt.isNullOrEmpty()) {
                        if (from == TYPE_RECORD) {
                            jump<NewTvFileDetailActivity> {
                                putExtra(TvConst.KEY_TYPE, data.ware_type)
                                putExtra(TvConst.KEY_IMAGE, data.ware_ppt)
                                putExtra(TvConst.KEY_ID, data.ware_id)
                                putExtra(TvConst.KEY_CLASS_ID, classId)
                            }
                        } else {
                            jump<NewTvPreviewActivity> {
                                putExtra(TvConst.KEY_ID, data.ware_id)
                                putExtra(TvConst.KEY_CLASS_ID, classId)
                            }
                        }

                    } else {
                        Toast.makeText(this, "暂无数据", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }
    }
}